package com.rocksdata.mc.business;

import android.app.Activity;

import com.alibaba.fastjson.JSON;
import com.ctz.commonframe.utils.AES;
import com.ctz.commonframe.utils.CommonUtil;
import com.ctz.commonframe.utils.Logger;
import com.rocksdata.mc.BuildConfig;
import com.rocksdata.mc.database.DatabaseManager;
import com.rocksdata.mc.entity.LoginResponse;
import com.rocksdata.mc.entity.StudentInfo;
import com.rocksdata.mc.entity.TeacherInfo;
import com.rocksdata.mc.http.HttpClient;
import com.rocksdata.mc.entity.UserInfo;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 陈堂正 on 2017/4/11.
 */

public class AccountManager implements BusinessInterface.IAccountManager {
    private static final String AES_KEY = "olL8j5uVy7iFUFdC";
    private static final String URL_LOGIN = BuildConfig.HOST + "/user/login";
    private static final String URL_MODIFY_PASSWORD = BuildConfig.HOST + "/user/modifyPassword";
    private static final String URL_UPLOAD_AVATAR = BuildConfig.HOST + "/user/uploadAvatar";
    private static final String URL_FEEDBACK = BuildConfig.HOST + "/feed_back/save_data_detail";

    private static BusinessInterface.IAccountManager instance;
    private BusinessInterface.IUserInfoManager userInfoManager;
    private BusinessInterface.IPushManager pushManager;

    private AccountManager(){
        userInfoManager = BusinessManager.getUserInfoManager();
        pushManager = BusinessManager.getPushManager();
    }

    static synchronized BusinessInterface.IAccountManager getInstance(){
        if(instance == null)
            instance = new AccountManager();
        return instance;
    }

    @Override
    public void login(final Activity context, final String account, final String password, final BusinessInterface.OnBusinessResultListener listener) {
        Map<String, String> map = new HashMap<>();
        map.put("userID", account);
        if (BuildConfig.PASSWORD_AES_FLAG) {
            map.put("password", AES.encrypt(password, BuildConfig.AES_KEY));
        } else {
            map.put("password", password);
        }
        HttpClient.post(URL_LOGIN, map, LoginResponse.class, new HttpClient.OnHttpResultListener<LoginResponse>(){

            @Override
            public void onResult(boolean isSuccess, List<LoginResponse> data, String msg) {
                if(isSuccess){
                    final LoginResponse lr = data.get(0);
                    final UserInfo userInfo = lr.getOperator();
                    UserInfoManager.saveAccessToken(lr.getAccess_token());
                    if (userInfo.getIsTeacher() == 1) {
                        userInfoManager.getTeacherInfoRemote(userInfo.getUserID(), new BusinessInterface.OnBusinessResultListener() {
                            @Override
                            public void onBusinessResult(boolean isSuccess, Object object, String message) {
                                if (isSuccess) {
                                    TeacherInfo info = (TeacherInfo) object;
                                    UserInfoManager.saveCurrentAccount(account);
                                    UserInfoManager.saveCurrentUserId(userInfo.getUserID());
                                    UserInfoManager.saveCurrentName(userInfo.getUserName());
                                    UserInfoManager.saveCurrentUserType(UserInfo.USER_TYPE_TEACHER);
                                    UserInfoManager.saveAvatar(info.getAvatar());
                                    UserInfoManager.saveDepartmentCode(info.getDepartment().getDepartmentCode());
                                    UserInfoManager.saveDepartmentName(info.getDepartment().getDepartmentName());
                                    onLoginSuccess();
                                    if (listener != null)
                                        listener.onBusinessResult(true, null, null);
                                } else {
                                    if (listener != null)
                                        listener.onBusinessResult(false, null, "登录失败，同步用户信息失败");

                                }
                            }
                        });
                    } else {
                        userInfoManager.getStudentInfoRemote(userInfo.getUserID(), new BusinessInterface.OnBusinessResultListener() {
                            @Override
                            public void onBusinessResult(boolean isSuccess, Object object, String message) {
                                if (isSuccess) {
                                    StudentInfo info = (StudentInfo) object;
                                    UserInfoManager.saveCurrentAccount(account);
                                    UserInfoManager.saveCurrentUserId(userInfo.getUserID());
                                    UserInfoManager.saveCurrentName(userInfo.getUserName());
                                    UserInfoManager.saveCurrentUserType(UserInfo.USER_TYPE_STUDENT);
                                    UserInfoManager.saveAvatar(info.getAvatar());
                                    UserInfoManager.saveClassCode(info.getStudentClass().getClassCode());
                                    UserInfoManager.saveClassName(info.getStudentClass().getClassName());
                                    onLoginSuccess();
                                    if (listener != null)
                                        listener.onBusinessResult(true, null, null);
                                } else {
                                    if (listener != null)
                                        listener.onBusinessResult(false, null, "登录失败，同步用户信息失败");

                                }
                            }
                        });
                    }

                }else{
                    if (listener != null)
                        listener.onBusinessResult(false, null, msg);
                }
            }
        });
    }

    public void onLoginSuccess(){
        DatabaseManager.initDb();
        if (pushManager != null) {
            pushManager.bindPushRelation();
        }
    }

    @Override
    public void modifyPassword(String oldPassword, String newPassword, final BusinessInterface.OnBusinessResultListener listener) {
        Logger.e("modifyPassword, oldPassword:" + oldPassword + ", newPassword:" + newPassword);
        Map<String, String> map = new HashMap<>();
        if (BuildConfig.PASSWORD_AES_FLAG) {
            map.put("oldPassword", AES.encrypt(oldPassword, BuildConfig.AES_KEY));
            map.put("newPassword", AES.encrypt(newPassword, BuildConfig.AES_KEY));
            map.put("secondPassword", AES.encrypt(newPassword, BuildConfig.AES_KEY));
        } else {
            map.put("oldPassword", oldPassword);
            map.put("newPassword", newPassword);
            map.put("secondPassword", newPassword);
        }
        HttpClient.post(URL_MODIFY_PASSWORD, map, new HttpClient.OnHttpResultListener<Object>(){

            @Override
            public void onResult(boolean isSuccess, List<Object> data, String msg) {
                if(isSuccess){
                    UserInfoManager.clearCurrentUserInfo();
                    listener.onBusinessResult(true, null, null);
                }else{
                    listener.onBusinessResult(false, null, msg);
                }
            }
        });
    }

    @Override
    public void uploadAvatar(String picturePath, final BusinessInterface.OnBusinessResultListener listener) {
        File file = new File(picturePath);
        if (!file.exists()) {
            listener.onBusinessResult(false, null, "图片不存在");
        } else {
            RequestParams params = new RequestParams(URL_UPLOAD_AVATAR);
            params.addHeader("Authorization", "Bearer " + UserInfoManager.getAccessToken());
            params.setMultipart(true);
            params.addBodyParameter("imageFile", file);
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        JSONObject data = jsonObject.getJSONObject("data");
                        String avatarUrl = data.getString("picPath");
                        UserInfoManager.saveAvatar(avatarUrl);
                        listener.onBusinessResult(true, avatarUrl, "上传头像成功");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    listener.onBusinessResult(false, null, "上传头像失败");
                }
                @Override
                public void onCancelled(CancelledException cex) {
                }
                @Override
                public void onFinished() {
                }
            });
        }

    }

    @Override
    public void feedback(String content, String contact, File image, final BusinessInterface.OnBusinessResultListener listener) {
        Map<String, String> map = new HashMap<>();
        map.put("content", content);
        map.put("contact", contact);
        HttpClient.postWithFile(URL_FEEDBACK, map, "picture", image, null, new HttpClient.OnHttpResultListener<Object>() {
            @Override
            public void onResult(boolean isSuccess, List<Object> data, String msg) {
                listener.onBusinessResult(isSuccess, null, msg);
            }
        });
    }

    @Override
    public void logout() {
        Logger.e("logout");
        UserInfoManager.clearCurrentUserInfo();
        DatabaseManager.closeDb();
//        RongIM.getInstance().disconnect();
//        RongIM.getInstance().logout();
        if (pushManager != null) {
            pushManager.unbindPushRelation();
        }
    }
}
